package com.example.campuslink.ui.activity.userOperation

import android.Manifest
import android.text.Editable
import android.text.TextWatcher
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import com.bumptech.glide.Glide
import com.example.campuslink.BR
import com.example.campuslink.R
import com.example.campuslink.commen.dialog.RegisterDialog
import com.example.campuslink.commen.tools.Sp
import com.example.campuslink.databinding.ActivityLoginBinding
import com.example.campuslink.ui.activity.BaseActivity
import com.example.campuslink.viewModel.userOperation.LoginViewModel

class LoginActivity : BaseActivity<ActivityLoginBinding, LoginViewModel>(
    LoginViewModel::class.java,
    R.layout.activity_login,
    BR.viewModel
) {
    override fun onRestart() {
        super.onRestart()
        if (Sp.getString(this, "userNumber", "") != "") {
            mViewDataBinding?.etNumber?.setText(Sp.getString(this, "userNumber", ""))
        }
    }

    override fun initView() {
        Sp.getSharedPrefs(this)
        mViewModel?.context = this
        mViewModel?.initDB(this)
        mViewModel?.addDefaultSchool()
     
        mViewModel?.addAdminUser()
        if (Sp.getString(this, "userNumber", "") != "") {
            mViewDataBinding?.etNumber?.setText(Sp.getString(this, "userNumber", ""))
        }
        mViewDataBinding?.btLogin?.setOnClickListener({
            mViewModel?.login(
                mViewDataBinding?.etNumber?.text.toString(),
                mViewDataBinding?.etPassword?.text.toString()
            )
        })
        mViewModel?.showRegisterDialog?.observe(this) {
            if (it) {
                RegisterDialog().show(supportFragmentManager, "registerDialog")
                mViewModel?.setShowRegisterDialog()
            }
        }
        mViewModel?.showPassword?.observe(this) {
            if (it) {
                Glide.with(this).load(R.drawable.ic_un_display).into(mViewDataBinding?.ivDisplay!!)
            } else {
                Glide.with(this).load(R.drawable.display).into(mViewDataBinding?.ivDisplay!!)
            }
        }
        mViewModel?.currentPosition?.observe(this) {
            mViewDataBinding?.etPassword?.setSelection(it)
        }
        mViewDataBinding?.etNumber?.setSelection(mViewDataBinding?.etNumber?.text?.length ?: 0)
        mViewDataBinding?.etPassword?.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun afterTextChanged(p0: Editable?) {
                mViewModel?.setCurrentPosition(p0?.length ?: 0)
            }

        })
    }
}